<?php

namespace common\models\admin;

use Yii;
use common\helpers\Url;
use common\helpers\ArrayHelper;
use common\helpers\StringHelper;
use youmbe\rbac\components\Configs;

/**
 * 后台管理员用户模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class AdminUser extends \common\base\BaseUser {

    const STATUS_ACTIVE = 10;
    const STATUS_DEFAULT = 0;
    const STATUS_DELETED = -1;

    /**
     * @inheritdoc
     */
    public static function getDb() {
        if (Configs::instance()->db !== null) {
            return Configs::instance()->db;
        }
        return parent::getDb();
    }

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return Configs::instance()->userTable;
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['username', 'mobile', 'auth_key', 'password_hash', 'realname'], 'required'],
            [['status', 'error_times', 'validated_at', 'company_id', 'created_at', 'updated_at'], 'integer'],
            [['username', 'realname'], 'string', 'max' => 50],
            [['mobile'], 'string', 'max' => 11],
            [['email'], 'string', 'max' => 64],
            [['avatar', 'password_hash', 'password_reset_token', 'profile'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['username'], 'unique'],
            [['mobile'], 'unique'],
            [['password_reset_token'], 'unique'],
            ['status', 'default', 'value' => self::STATUS_DEFAULT],
            ['status', 'in', 'range' => [self::STATUS_ACTIVE, self::STATUS_DEFAULT, self::STATUS_DELETED]],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'mobile' => '手机号',
            'email' => '邮箱',
            'avatar' => '头像',
            'auth_key' => '密钥',
            'password_hash' => 'HASH密码',
            'password_reset_token' => '密码重置TOKEN',
            'realname' => '真实姓名',
            'profile' => '个人简介',
            'rolename' => '管理员角色',
            'error_times' => '错误次数',
            'status' => '状态',
            'validated_at' => '校验时间',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    /**
     * @inheritdoc
     */
    public function getRolename() {
        $manager = Yii::$app->getAuthManager();
        $roles = $manager->getRolesByUser($this->id);
        $rolename = '';
        foreach ($roles as $role) {
            $rolename .= $role->name . ' ';
        }
        return $rolename;
    }

    public function getPortrait() {
        $avatar = $this->avatar ?: ArrayHelper::getValue(Yii::$app->params, ['defaultImage', 'avatar'], '/assets/avatar/default.png');
        if (Url::isRelative($avatar)) {
            $avatar .= '?x-oss-process=image/resize,m_fill,h_100,w_100';
        }
        return Url::attach($avatar);
    }

    public function getUserName() {
        return $this->username;
    }

    public function getCompanys() {
        return $this->hasMany(AdminUserCompany::class, ['user_id' => 'id'])->orderBy([
            'current' => SORT_DESC
        ])->with('company');
    }

    public function getCompany() {
        if ($this->company_id) {
            return $this->hasOne(AdminCompany::class, ['id' => 'company_id']);
        }
        return $this->hasOne(AdminCompany::class, ['id' => 'store_id'])->via('adminStores');
    }

    public function getCompanyIds() {
        $session = Yii::$app->session;
        if ($session->has('cid')) {
            return $session->get('cid');
        }
        $company = $this->company;
        if ($company) {
            $id = $company->company_id;
            $session->set('cid', $id);
            return $id;
        }
        return 0;
    }

    public function getRoles() {
        $manager = Yii::$app->getAuthManager();
        $userRoles = $manager->getRolesByUser($this->id);
        return $roles = array_keys($userRoles);
    }

    public function getAuthRoles() {
        $manager = Yii::$app->getAuthManager();
        $userRoles = $manager->getRolesByUser($this->id);
        return array_keys($userRoles);
    }

    public function getStores() {
        $authRuleData = $this->getRuleData();
        return AdminCompany::find()->andWhere([
            'id' => ArrayHelper::getValue($authRuleData, 'store', [])
        ])->all();
    }

    public function getAdminStores() {
        return $this->hasMany(\common\models\shop\ShopStoreAdminer::class, ['admin_id' => 'id']);
    }

    public function getStoreId() {
        if ($this->company_id) {
            return $this->company_id;
        }
        return ArrayHelper::getValue($this->adminStores, [0, 'store_id'], 0);
    }

    public function getMaskMobile() {
        return StringHelper::maskChar($this->mobile);
    }

    public function fields() {
        return [
            'id',
            'name' => 'username',
            'mobile' => 'maskMobile',
            'avatar' => 'portrait',
            'introduction' => 'profile',
            'company',
            'status',
            'roles',
            'stores',
            'storeId',
            'menus' => 'authMenus',
            'created_at',
        ];
    }

}
